package com.yjd.api.message;
import com.yjd.comm.app.service.IPushRecordService;
import com.yjd.comm.base.control.BaseControl;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.base.model.PagerHtmlModel;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.PagerUtil;
import com.yjd.comm.util.ServletUtil;
import com.yjd.comm.util.StringUtil;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 获取消息接口（各种推送的消息等）
 * Created by yangchangyan on 2017/8/30.
 */
@Controller("com.yjd.api.message.MessageControl")
@Scope("prototype")
@RequestMapping("/message")
public class MessageControl extends BaseControl {

    @Resource
    private IPushRecordService pushRecordService;

    /**
     * 返回用户的未读消息数（推送的消息都是未读的，app点击未读信息，进入消息列表，这时会更新消息为已读），
     * Created by yangchangyan on 2017/8/31.
     *
     * @param
     * @return
     * @throws
     */
    @RequestMapping(value = "/unread")
    public void unReadMessageCount(Long user_id) throws Exception {
        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);

        user_id = super.getSessionUserId();
        if(StringUtil.isEmpty(user_id)){
            paramMap.put("unReadCount", 0);
            this.successData(paramMap);
            return;
        }

        // 获取用户未读消息数 是否已读（0 未读 1已读）
        long unRead = pushRecordService.getModelListCount(FrameUtil.newHashMap("user_id", user_id, "readed", 0), DbWREnums.READ);

        paramMap.put("unReadCount", unRead);
        this.successData(paramMap);
    }

    /**
     * 获取用户消息列表
     * Created by yangchangyan on 2017/8/31.
     *
     * @param
     * @return
     * @throws
     */
    @RequestMapping(value = "/list")
    public void messageList(Long user_id) throws Exception {

        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);

        user_id = super.getSessionUserId();
        if(StringUtil.isEmpty(user_id)){
            this.successData(paramMap);
            return;
        }

        paramMap.put("user_id", user_id);
        paramMap.put("sort", " create_time desc");

        PagerHtmlModel pager = PagerUtil.getPagerHtmlModel(
                this.pushRecordService.getPageModel(paramMap, DbWREnums.READ), paramMap,
                ServletUtil.getUrl("/message/list"));

        paramMap.put("messageList", pager.getPagerModel().getDataList());

        // 更新用户此刻之前的推送消息为已读
        paramMap.put("user_id", user_id);
        paramMap.put("unread", 0);
        paramMap.put("readed", 1); // 将满足上面条件的未读消息更像为已读
        pushRecordService.updateByMap(paramMap, DbWREnums.READ);

        this.successData(paramMap);
    }
}
